<?php

namespace app\common\model;

use think\Model;
use app\common\model\MoneyLog;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
            return $value;
        }
        return cdnurl($value);
    }

    /**
     * 获取会员的下级数量
     */
    public function getChildrenNumAttr($value, $data)
    {
        return User::where('top_id', $data['id'])->count();
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param   string $value
     * @param   array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array) json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object) $value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     * @param string $from_user_id    和哪个用户有关
     * @param string $type    和哪个用户有关 1=系统奖励,2=下级发广告奖励,3=下级下单奖励,4=看广告奖励
     */
    public static function money($money, $user_id, $memo, $from_user_id = 0, $type = MoneyLog::TYPE_SYSTEM)
    {
        $user = self::get($user_id);
        if ($user && $money != 0) {
            $before = $user->money;
            $after = $user->money + $money;
            //更新会员信息
            $update = $user->save(['money' => $after]);
            //写入日志
            MoneyLog::create([
                'user_id' => $user_id, 
                'money' => $money, 
                'before' => $before, 
                'after' => $after, 
                'memo' => $memo,
                'from_user_id' => $from_user_id,
                'type' => $type,
            ]);

            return $update === false ? false : true;
        }

        return false;
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $score != 0) {
            $before = $user->score;
            $after = $user->score + $score;
            $level = self::nextlevel($after);
            //更新会员信息
            $user->save(['score' => $after, 'level' => $level]);
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    /**
     * 获取用户基本信息
     */
    public static function getBaseInfo($user_id, $field = "id,nickname,avatar,mobile")
    {
        return self::cache(300)->field($field)->find($user_id);
    }


    /**
     * 获取用户基本脱敏信息
     */
    public static function getBaseInfoNosense($user_id)
    {
        $info = self::getBaseInfo($user_id);
        if ($info && isset($info['mobile'])) {
            try {
                $info['mobile'] = preg_replace("/(\d{3})(\d{4})(\d{4})/", "$1****$3", $info['mobile']);
            } catch (\Exception $e) {
                //throw $th;
            }
        }
        return $info;
    }

    /**
     * 获取用户的默认地址
     */
    public static function getDefaultAddress($user_id)
    {
        $address = \think\Db::name('self_address')->where(array('user_id' => $user_id))->order('is_default desc,id desc')->find();
        return $address ? $address : '';
    }

    /**
     * 获取用户的上级
     */
    public static function getTopUser($user){
        if(!$user) return NULL;
        if(!$user instanceof User){
            $user = self::field('id,top_id')->find($user);
        }
        if(!$user || !$user->top_id) return NULL;

        return self::field('id,nickname,avatar')->find($user->top_id);
    }

    public static function setTopUser($user){
        if(!$user) return NULL;
        if(!$user instanceof User){
            $user = self::field('id,top_id')->find($user);
        }
        
        if($user->top_id) return false;

        $top_user_id = input('share_from/d', 0);

        if(!$top_user_id) return false;

        $user->top_id = $top_user_id;

        if($user->save()){
            \app\common\model\score\Task::execute_task(3, $top_user_id);    //新手任务
            \app\common\model\score\Task::execute_task(4, $top_user_id);    //日常邀请
        }
    }
}
